package action.newelifile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;

import org.apache.commons.net.ftp.FTPFile;

import action.adapter.FTPFavoriteAdapter;
import action.adapter.FavoriteFileAdapter;
import action.pojo.FtpConnect;
import action.util.FtpConnectSQLITE;
import action.util.Tool;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class AddressFTPActivity extends Activity{
	Button historyButton,favoriteButton,cancel;
	ListView popupListView;
	TextView txtViewEmpty;
	RelativeLayout clearButton;
	FtpConnectSQLITE ftpConnectSQLITE;
	int flagviewhistory=0;
	
	ProgressDialog mProgressDialog;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	public static final int DIALOG_PROGRESS = 1;
	AsyncTask<String, String, Void> asyn;
	public static final int DIALOG_GETTING_FILE =0;

	AsyncTask<String, String, String> asyntask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.popup_address);
		getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

		ftpConnectSQLITE = new FtpConnectSQLITE(this);
		ftpConnectSQLITE.open();

		initAttribute();

		super.onCreate(savedInstanceState);

	}

	public void initAttribute(){
		historyButton = (Button)findViewById(R.id.historyButton);
		favoriteButton = (Button)findViewById(R.id.favoriteButton);
		popupListView = (ListView)findViewById(R.id.popupListView);
		clearButton = (RelativeLayout)findViewById(R.id.clearButton);
		cancel = (Button)findViewById(R.id.cancel);
		cancel.setText(getString(R.string.cancel));
		txtViewEmpty = (TextView)findViewById(R.id.txtViewEmpty);

		historyButton.setOnClickListener(historyClick());
		favoriteButton.setOnClickListener(favoriteClick());
		popupListView.setOnItemClickListener(onPopupListClick());
		historyButton.performClick();
		
		cancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				setResult(0);
				finish();
			}
		});
		
	}
	
	// clear history button
	private OnClickListener clearHistory(){
		OnClickListener action = new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(Tool.position == 3)
					Tool.list_history_ftp = new ArrayList<FtpConnect>();
					finish();
			}
		};
		return action;
	}
	
	// process history
	public OnClickListener historyClick(){
		OnClickListener onclick = new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				flagviewhistory=1;
				historyButton.setCompoundDrawablesWithIntrinsicBounds(null,null, null, getResources().getDrawable(R.drawable.arrowup) );
				favoriteButton.setCompoundDrawablesWithIntrinsicBounds(null,null, null , null);
				clearButton.setOnClickListener(clearHistory());
				ArrayList<FtpConnect> temp = new ArrayList<FtpConnect>();
				if(Tool.position==3)
					temp.addAll(Tool.list_history_ftp);
				System.out.println(" tool list history == " + Tool.list_history_ftp);
				Collections.reverse(temp);
				
				if(temp!=null && temp.size()>0){
					popupListView.setVisibility(ListView.VISIBLE);
					popupListView.setAdapter(new FTPFavoriteAdapter(AddressFTPActivity.this, R.layout.history_detail, temp));
					txtViewEmpty.setVisibility(TextView.GONE);
				}
				else{
					popupListView.setVisibility(ListView.GONE);
					txtViewEmpty.setVisibility(TextView.VISIBLE);
					txtViewEmpty.setText("History empty");
				}
			}
		};
		return onclick;
	}

	//clear favorite Button
	private OnClickListener clearFavorite(){
		OnClickListener action = new OnClickListener() {			
			public void onClick(View v) {
				Tool.list_favorite_ftp = new ArrayList<FtpConnect>();
				if(Tool.position==3){
					ftpConnectSQLITE.open();
					ftpConnectSQLITE.deleteFavorite();
				}
			}
		};
		return action;
	}
	public OnClickListener favoriteClick(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				flagviewhistory=2;
				favoriteButton.setCompoundDrawablesWithIntrinsicBounds(null,null, null, getResources().getDrawable(R.drawable.arrowup) );
				historyButton.setCompoundDrawablesWithIntrinsicBounds(null,null, null , null);
				clearButton.setOnClickListener(clearFavorite());
				ArrayList<FtpConnect> temp = new ArrayList<FtpConnect>();
				if(Tool.list_favorite_ftp != null)
					temp.addAll(Tool.list_favorite_ftp);
				
				if(temp!=null && temp.size()>0){
					popupListView.setVisibility(ListView.VISIBLE);
					popupListView.setAdapter(new FTPFavoriteAdapter(AddressFTPActivity.this, R.layout.history_detail, temp));
					txtViewEmpty.setVisibility(TextView.GONE);
				}
				else{
					popupListView.setVisibility(ListView.GONE);
					txtViewEmpty.setVisibility(TextView.VISIBLE);
					txtViewEmpty.setText("Favorites empty");
				}
			}
		};
		return onclick;
	}
	public OnItemClickListener  onPopupListClick(){
		OnItemClickListener onclick = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				try{
					if(flagviewhistory==1){
						System.out.println("vao dau the");
					}else if(flagviewhistory ==2){
						
						Tool.connect = (FtpConnect)parent.getItemAtPosition(position);
						final FTPFile file = new FTPFile();
						System.out.println(" postion == " + position);
						System.out.println("aaa == " + Tool.connect.getPath()+File.separator + Tool.connect.getName());
						file.setName(Tool.connect.getPath()+File.separator + Tool.connect.getName());
						
						if(file.isDirectory()){
							System.out.println(" this is a folder");
						}else{
							System.out.println("vo day ko");
							asyntask = new AsyncTask<String, String, String>() {

								protected void onPreExecute() {
									showDialog(DIALOG_GETTING_FILE);
								}

								protected void onProgressUpdate(String... progress) {
									mProgressDialog.setProgress(Integer.parseInt(progress[0]));
								}
								void process(){
									try {
										boolean flag = Tool.connects();
										if (flag==true){
											File f = new File(Environment.getExternalStorageDirectory()+File.separator+"elifiledownload"+File.separator);

											if(!f.exists()){
												f.mkdir();
											}

											f = new File(Environment.getExternalStorageDirectory()+File.separator+"elifiledownload"+File.separator+Tool.connect.getName());
											if(!f.exists()){
												f.createNewFile();
											}

											BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(f));
											InputStream input =Tool.client.retrieveFileStream(Tool.connect.getPath()+File.separator +Tool.connect.getName());
											
											byte[] buffer = new byte[1024];
											int len1 = 0;
											long total = 0;				        
											while ((len1 = input.read(buffer)) > 0) {
												total += len1;
												publishProgress(""+((total*100)/file.getSize()));
												output.write(buffer, 0, len1);
											}
											if(output!=null)output.close();
											if(input!=null)input.close();


											if(f.canRead()){
												Intent intent = new Intent(Intent.ACTION_VIEW);
												if(Tool.checkExtendFile(Tool.connect.getName(), ".txt")){
													intent.setDataAndType(Uri.fromFile(f),"text/*");

												}else if(Tool.checkExtendFile(Tool.connect.getName(), ".xml")){
													intent.setDataAndType(Uri.fromFile(f),"text/*");
												}else if(Tool.checkExtendFile(Tool.connect.getName(), ".apk")){
													intent.setDataAndType(Uri.fromFile(f),"application/vnd.android.package-archive");
												}

												else if (Tool.checkExtendFile(Tool.connect.getName(), ".FLV")
														|| Tool.checkExtendFile(Tool.connect.getName(), ".3gp")
														|| Tool.checkExtendFile(Tool.connect.getName(), ".avi")) {
													intent.setDataAndType(Uri.fromFile(f), "video/*");
												} else if (Tool.checkExtendFile(Tool.connect.getName(), ".mp3")) {
													intent.setDataAndType(Uri.fromFile(f), "audio/*");
												} else if (Tool.checkExtendFile(Tool.connect.getName(), ".doc")
														|| Tool.checkExtendFile(Tool.connect.getName(), ".docx")) {
													intent.setDataAndType(Uri.fromFile(f), "text/*");
												} else if (Tool.checkExtendFile(Tool.connect.getName(), ".ppt")
														|| Tool.checkExtendFile(Tool.connect.getName(), ".pptx")) {
													intent.setDataAndType(Uri.fromFile(f), "text/*");
												} else if (Tool.checkExtendFile(Tool.connect.getName(), ".xls")
														|| Tool.checkExtendFile(Tool.connect.getName(), ".xlsx")) {
													intent.setDataAndType(Uri.fromFile(f), "text/*");
												} else if (Tool.checkExtendFile(Tool.connect.getName(), ".zip")
														|| Tool.checkExtendFile(Tool.connect.getName(), ".rar")) {
													intent.setDataAndType(Uri.fromFile(f), "video/*");
												} else if (Tool.checkExtendFile(Tool.connect.getName(), ".jpg")
														|| Tool.checkExtendFile(Tool.connect.getName(), ".jpeg")
														|| Tool.checkExtendFile(Tool.connect.getName(), ".png")
														|| Tool.checkExtendFile(Tool.connect.getName(), ".bmp")
														|| Tool.checkExtendFile(Tool.connect.getName(), ".gif")) {
													intent.setDataAndType(Uri.fromFile(f), "image/*");
												}
												startActivity(intent);
											}
										}	
										else{
											System.out
											.println(" connect fail");
										}
										if(Tool.client.isConnected()){
											Tool.client.logout();
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
								}

								protected String doInBackground(String... params) {
									process();				
									return null;
								}

								protected void onPostExecute(String unused) {
									dismissDialog(DIALOG_GETTING_FILE);
									finish();
								}

							};		
							asyntask.execute("");	
						}
					}
				}catch (Exception e) {
				}
			}
		};
		return onclick;
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_GETTING_FILE:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage(getResources().getString(R.string.gettingfile));
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		case DIALOG_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}
}
